﻿using FrameWork.Core.Enum;
using FrameWork.Data.Enum;
using FrameWork.Services;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Data;

namespace AncheStart.Converter
{
    public class PrecisionConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            //读取配置文件
            EnumUnitType parameterEnumUnitType = (EnumUnitType)System.Enum.Parse(typeof(EnumUnitType), parameter.ToString());
            //
            var unitsInfo = GlobalConstant.UnitsInfos.Where(P => P.UnitType == parameterEnumUnitType).FirstOrDefault();
            //
            var unitList = JsonConvert.DeserializeObject<List<EnumberEntity>>(unitsInfo.UnitCode);
            //
            var selectUnit = unitList.Where(p => p.EnumValue == unitsInfo.SelectUnitValue).FirstOrDefault();
            //精度
            int decimalPlaces = unitsInfo.DecimalPlaces;
            //
            string selectUnitCode = unitsInfo.SelectUnitCode;

            //
            string precesionPattern = $"F{decimalPlaces}";
            if (value != null)
            {
                double convertedValue = (double)value / unitsInfo.SelectUnitValue;

                string resValue = convertedValue.ToString(precesionPattern) + selectUnitCode;
                return resValue;
            }
            else
            {
                double convertedValue = (double)(value ?? 0 / unitsInfo.SelectUnitValue);

                string resValue = convertedValue.ToString(precesionPattern) + selectUnitCode;
                return 0;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}